﻿using System;
using System.Collections.Generic;
using System.Linq;
using LayeredArchitectureSample.DataTransferObjects;
using LayeredArchitectureSample.DomainModel;
using LayeredArchitectureSample.Infrastructure.Services;
using LayeredArchitectureSample.ServiceContracts;

namespace LayeredArchitectureSample.RandomDataProviders
{
    class RandomRouteProvider : IRandomRouteProvider
    {
        private readonly IServiceOperationInvoker<IRemoteRouteRepository> _routeRepository;

        public RandomRouteProvider(IServiceOperationInvoker<IRemoteRouteRepository> routeRepository)
        {
            if (routeRepository == null) throw new ArgumentNullException("routeRepository");

            _routeRepository = routeRepository;
        }

        /// <summary>
        /// 
        /// </summary>
        /// <returns></returns>
        /// <exception cref="CannotProvideRandomObjectException"></exception>
        public RouteDto GetRandomRoute()
        {
            var random = new Random((int)DateTime.UtcNow.Ticks);
            
            List<RouteDto> allRoutes = _routeRepository.Invoke(r => r.GetAll()).ToList();
            
            if (allRoutes.Count < 1)
            {
                throw new CannotProvideRandomObjectException("Need at least one route specified in the repository to pick a random route.");
            }

            return allRoutes[random.Next(allRoutes.Count)];
        }
    }
}